import { defineStore } from 'pinia';

// 创建安全的存储方法
const safeStorage = {
	get(key, defaultValue = null) {
		try {
			const value = uni.getStorageSync(key);
			return value || defaultValue;
		} catch (err) {
			console.error(`获取${key}失败:`, err);
			return defaultValue;
		}
	}
};

// 定义 store
export const useUserStore = defineStore('user', {
	state: () => ({
		index: 0,
		token: '',
		familyName: '',
		members: [],
		flashFlag: false
	}),
	getters: {},
	actions: {
		changeIndex(index) {
			this.index = index;
		},
		setToken(val) {
			this.token = val;
		},
		setFlashFlag(val) {
			this.flashFlag = val;
		},
		setFamilyName(val) {
			this.familyName = val;
		},
		setMembers(val) {
			this.members = val;
		},
		// 初始化状态
		initState() {
			const token = safeStorage.get('token', '');
			const familyName = safeStorage.get('familyName', '');
			const members = safeStorage.get('members', []);

			this.token = token;
			this.familyName = familyName;
			this.members = members;
		}
	},
	persist: {
		enabled: true,
		strategies: [
			{
				key: 'user',
				storage: {
					getItem(key) {
						try {
							return uni.getStorageSync(key);
						} catch (err) {
							console.error('获取存储失败:', err);
							return null;
						}
					},
					setItem(key, value) {
						try {
							uni.setStorageSync(key, value);
						} catch (err) {
							console.error('设置存储失败:', err);
						}
					}
				}
			}
		]
	}
});